﻿/*
 *  Copyright 2009 Duck Pond, Inc.
 *  http://www.duckpondinc.com/
 *  
 *  This file is part of Server Watch & Alert.
 *
 *  Server Watch & Alert is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  Server Watch & Alert is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with Server Watch & Alert.  If not, see <http://www.gnu.org/licenses/>.
 *  
 * */

using System;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using System.Xml.Serialization;

namespace DuckPond.ServerWatchAlert.Core.TestActions
{
    //[XmlElement(ElementName = "http-regex-test")]
    public class HttpRegexTest : TestAction
    {
        /////////////////////
        // FIELDS
        /////////////
        protected Regex _RegexCache;


        /////////////////////
        // PROPERTIES
        /////////////
        [XmlAttribute("server")]
        public string Server { get; set; }

        [XmlAttribute("timeout")]
        public int Timeout { get; set; }

        [XmlAttribute("url")]
        public string Url { get; set; }

        [XmlAttribute("regex")]
        public string RegEx { get; set; }


        /////////////////////
        // METHODS: override
        /////////////
        public override TestResult PerformAction()
        {
            DateTime now = DateTime.Now;

            if (_RegexCache == null)
            {
                _RegexCache = new Regex(this.RegEx, RegexOptions.Multiline | RegexOptions.Compiled);
            }

            // prepare url
            string url = this.Url;

            // prepare request
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.AllowAutoRedirect = true;
            if (this.Timeout > 0)
            {
                request.Timeout = this.Timeout * 1000;
            }

            // get response
            string responseBody;
            try
            {
                HttpWebResponse response
                    = (HttpWebResponse)request.GetResponse();

                // load response
                using (Stream responseStream = response.GetResponseStream())
                using (StreamReader responseReader = new StreamReader(responseStream))
                {
                    responseBody = responseReader.ReadToEnd();
                }

                // close response object
                response.Close();
            }
            catch (WebException exc)
            {
                // probably a timeout.
                return new TestResult() 
                { 
                    Success = false, 
                    Test = this, 
                    TimeStamp = now, 
                    Message = exc.Message,
                };
            }

            // inspect the response body
            bool isMatch = _RegexCache.IsMatch(responseBody);
            if (!isMatch)
            {
                return new TestResult()
                { 
                    Success = false, 
                    Test = this, 
                    TimeStamp = now, 
                    Message 
                        = "Response is missing expected content."
                        + "\r\n-------- response --------\r\n"
                        + responseBody,
                };
            }

            // return
            return new TestResult() 
            { 
                Success = true, 
                Test = this, 
                TimeStamp = now,
                Message = "Ok.",
            };
        }
    }
}
